<template>
  <div>
    <!-- ADD dialog start -->
    <el-dialog
        v-model="dialogVisible"
        title="创建训练模型"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="makeData" status-icon ref="formRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="模型选择" prop="modelSelect">
            <el-radio-group v-model="mdeolRadio" class="ml-4">
              <el-radio label="1">创建新模型</el-radio>
              <el-radio label="2">已有模型</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="模型名称" prop="modelName">
            <el-input v-model="makeData.modelName"></el-input>
          </el-form-item>
          <el-form-item>
            <!-- imgset select start -->
            <el-select v-model="imgsetValue" placeholder="数据集选择">
              <el-option
                  v-for="item in imgset"
                  :key="item.imgsetName"
                  :label="item.imgsetName"
                  :value="item.imgsetId"
              >
                <span style="float: left">{{ item.imgsetName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                  {{ item.imgsetId }}
                </span>
              </el-option>
            </el-select>
            <!-- imgset select end -->
          </el-form-item>
          <el-form-item>
            <!-- imgset select start -->
            <el-select v-model="imgsetValue" placeholder="标签集选择">
              <el-option
                  v-for="item in imgset"
                  :key="item.imgsetName"
                  :label="item.imgsetName"
                  :value="item.imgsetId"
              >
                <span style="float: left">{{ item.imgsetName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                  {{ item.imgsetId }}
                </span>
              </el-option>
            </el-select>
            <!-- imgset select end -->
          </el-form-item>
          <el-form-item>
            <!-- imgset select start -->
            <el-select v-model="imgsetValue" placeholder="外部数据集选择">
              <el-option
                  v-for="item in imgset"
                  :key="item.imgsetName"
                  :label="item.imgsetName"
                  :value="item.imgsetId"
              >
                <span style="float: left">{{ item.imgsetName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                  {{ item.imgsetId }}
                </span>
              </el-option>
            </el-select>
            <!-- imgset select end -->
          </el-form-item>
          <el-form-item>
            <!-- imgset select start -->
            <el-select v-model="imgsetValue" placeholder="外部标签集选择">
              <el-option
                  v-for="item in imgset"
                  :key="item.imgsetName"
                  :label="item.imgsetName"
                  :value="item.imgsetId"
              >
                <span style="float: left">{{ item.imgsetName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                  {{ item.imgsetId }}
                </span>
              </el-option>
            </el-select>
            <!-- imgset select end -->
          </el-form-item>

          <el-form-item label="模型描述" prop="describe">
            <el-input
                type="textarea"
                resize="none"
                :autosize="{minRows:4,maxRows:4}"
                placeholder="请输入该模型的具体描述"
                v-model="makeData.describe"
                autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="submitForms">提交</el-button>
            <el-button @click="resetForm('signUp')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- ADD dialog end -->

    <!-- Modify dialog start -->
    <el-dialog
        v-model="modifyVisible"
        title="修改数据集"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="modifyData" status-icon ref="modifyRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="名称" prop="imageSetName">
            <el-input v-model="modifyData.imgsetName"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="describe">
            <el-input
                type="textarea"
                resize="none"
                :autosize="{minRows:4,maxRows:4}"
                placeholder="请输入该数据集的具体描述"
                v-model="modifyData.describe"
                autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="modifySubmitForms">提交</el-button>
            <el-button @click="resetForm('signUp')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- Modify dialog end -->

    <!-- list_data start  -->
    <div class="list_data_box">
      <div class="line"></div>
      <div class="gui_box">
        <el-input
            v-model="input3"
            placeholder="Please input"
            class="input-with-select"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <el-button @click="dialogVisible = true"  type="primary" style="margin-left: 340px;">训练模型</el-button>
        <el-button type="primary" :icon="Refresh" @click="getList"/>
      </div>

      <div v-for="(item,index) in displayedData" class="data_box">
        <!--        <span style="font-size:20px;margin-left:20px">{{ item.imgsetId }}</span>-->
        <div style="background-color: #f7f4f4;width:100%;height:45px;color:black">
          <span style="margin-left: 20px;line-height:45px">{{ item.modelName }}</span>
          <span style="margin-left: 20px;line-height:45px">模型ID：{{item.modelId}}</span>
          <el-button :icon="CaretRight" @click="handleView(index)" style="margin-left:10px;border: none;background-color: transparent">训练</el-button>
        </div>
        <div style="background-color: #f7f4f4;width:100%;height:35px;color:black;display:flex">
          <div class="data-box-content"><span>部署方式</span></div>
          <div class="data-box-content"><span>版本</span></div>
          <div class="data-box-content"><span>训练状态</span></div>
          <div class="data-box-content"><span>训练日志</span></div>
          <div class="data-box-content"><span>操作</span></div>
        </div>
        <div style="width:100%;height:55px;color:black;display:flex">
          <div class="data-box-content"><span style="line-height:48px">{{ item.deploymentMethod }}</span></div>
          <div class="data-box-content"><span style="line-height:48px">V1</span></div>
          <div class="data-box-content">
            <span style="line-height:48px">{{ item.status }}</span>
            <el-progress :percentage="item.progress" style="top: -10px;"/>
          </div>
          <div class="data-box-content">
            <el-button :icon="Search" style="margin-top:10px;margin-left:10px;border: none;background-color: transparent">查看</el-button>
          </div>
          <div class="data-box-content">
            <el-button :icon="Search" @click="handleView(index)" style="margin-top:10px;margin-left:-6px;border: none;background-color: transparent"></el-button>
            <el-button :icon="EditPen" @click="modifyView(index)" style="margin-top:10px;border: none;background-color: transparent"></el-button>
            <el-button :icon="Delete" @click="removeView(index)" style="margin-top:10px;border: none;background-color: transparent"></el-button>
          </div>
        </div>
      </div>
      <div class="demo-pagination-block" style="margin-left:30px;margin-top:15px">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- list_data end  -->

  </div>
</template>

<script>
import {onMounted, ref, reactive} from "vue";
import {ElDialog, ElLoading, ElMessage, ElForm, ElMessageBox, ElTable, ElTableColumn, ElPagination  } from 'element-plus'
import datasets from '@/api/datasets'
import httpHelper from "@/api/httpHelper";
import router from "@/router";
import { Delete, Search, Refresh, EditPen, CaretRight } from '@element-plus/icons-vue'
import task from "@/api/task";
import train from "@/api/train"

export default {
  name: "ModelCenter",
  components:{
    ElDialog,
    ElLoading,
    ElForm,
    ElTable,
    ElTableColumn,
    ElPagination,
    EditPen,
  },

  setup(){
    // select选择控制器
    const mdeolRadio = ref('1') // 模型选择

    // 筛选指标
    const screenValue = ref('')
    const screenOptions = [
      {
        value: '模型兼顾Precision和Recall',
        label: '模型兼顾Precision和Recall',
      },
      {
        value: 'Precision最高',
        label: 'Precision最高',
      },
      {
        value: 'Recall最多',
        label: 'Recall最多',
      },
      {
        value: 'ACC最大',
        label: 'ACC最大',
      },
      {
        value: 'Loss最小',
        label: 'Loss最小',
      },
    ]

    // 控制创建数据集的弹出层，默认为不弹出
    const dialogVisible = ref(false)
    let loadingInstance = null

    // 控制修改数据集的弹出层，默认为不弹出
    const modifyVisible = ref(false)

    // form数据模型
    const makeData = ref({
      imgsetName:'',
      describe:''
    })
    const formRef = ref(null)

    // form修改数据模型
    const modifyData = ref({
      imgsetName:'',
      describe:''
    })
    const modifyRef = ref(null)
    let imgsetId = 0

    const imgsetValue = ref('')
    let imgset = ref([])

    // 渲染数据模型
    let listData = reactive([])
    const selectedKeys = reactive([])
    let displayedData = reactive([])

    // 分页控制
    const currentPage = ref(1);
    const pageSize = ref(5);

    // 加载函数
    onMounted(()=>{
      getList()
    });


    // 查
    function getList(){
      let userData = JSON.parse(localStorage.getItem('userData'))
      console.log(userData)
      let da = {}
      da.userId = userData.userId
      train.list(da).then(res => {
        console.log(res)
        listData.length = 0
        listData.splice(0,res.data.length,...res.data)

        listData.forEach(function(element){
          switch (element.dataSources){
            case 0:element.dataSources = "我的数据集";break;
            case 1:element.dataSources = "公开数据集";break;
          }
          switch (element.deploymentMethod){
            case 0:element.deploymentMethod = "系统部署";break;
          }
          switch (element.algorithm){
            case 0:element.algorithm = "高性能";break;
            case 1:element.algorithm = "小样本";break;
            case 2:element.algorithm = "高精度";break;
          }
          switch (element.status){
            case 0:element.status = "训练未开始";break;
            case 1:element.status = "训练中";break;
            case 2:element.status = "训练完成";break;
            case 3:element.status = "训练暂停";break;
            case 4:element.status = "训练异常";break;
          }
        })
        currentPage.value = 1
        pageSize.value = 5
        const start = (currentPage.value - 1) * pageSize.value
        const end = start + pageSize.value
        displayedData.length = 0
        displayedData.splice(start, end, ...listData.slice(start, end))

        task.about(da).then(res =>{
          imgset.value = res.data.imgset
        })
      })
    }

    // 转影像
    const handleView = (index) => {
      router.push({ name: 'Imgs', params: { imgsetId: displayedData[index].imgsetId }})
    };

    // 改
    const modifyView = (index) => {
      console.log(index)
      console.log(displayedData[index])
      modifyVisible.value = true
      modifyData.value.imgsetName = displayedData[index].imgsetName
      modifyData.value.describe = displayedData[index].represent
      imgsetId = displayedData[index].imgsetId
    };

    // 删
    function removeView(index){
      console.log(displayedData[index].modelId)
      if(index === null){
        ElMessageBox.alert('请选择需要删除的数据！','Warning',{
          confirmButtonText:"OK"
        })
      }else{
        ElMessageBox.confirm(
            '您确定想要删除选中的数据集吗？',
            'Warning',
            {
              confirmButtonText:'OK',
              cancelButtonText:'Cancel',
              type: 'warning'
            }
        ).then(() => {
          console.log(displayedData[index].status)
          if(displayedData[index].status === "训练未开始" || displayedData[index].status === "寻来你暂停"){
            let da = {}
            da.modelId = displayedData[index].modelId
            train.remove(da).then(res =>{
              console.log(res)
              if(res.code == 200){
                console.log(res)
                ElMessage.success("删除成功")
                getList()
              }else{
                ElMessage.error("error！")
              }
            })
          }else{
            ElMessage({
              type:'info',
              message:"模型训练中，不建议删除"
            })
          }
        }).catch(() => {
          ElMessage({
            type:'info',
            message:"取消删除"
          })
        })
      }
    }

    // 关闭遮罩层
    function handleBeforeClose(done){
      loadingInstance.close()
      done()
    }

    // 增
    const submitForms = () => {
      formRef.value.validate((valid) => {
        if(valid){
          let da = {}
          console.log(formRadio.value)
          console.log(imgsetValue.value)
          console.log(screenValue.value)
          da.modelName = makeData.value.modelName
          da.dataSources = formRadio.value
          da.deploymentMethod = arrangeRadio.value
          da.algorithm = algorithmRadio.value
          da.screeningIndicators = screenValue.value
          da.environment = environmentRadio.value
          da.represent = makeData.value.describe
          da.datasetId = imgsetValue.value
          da.userId = JSON.parse(localStorage.getItem('userData')).userId
          console.log(da)

          // da.imgsetName = makeData.value.imgsetName;
          // da.represent = makeData.value.describe;
          // da.userId = JSON.parse(localStorage.getItem('userData')).userId
          //
          train.make(da).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("创建成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })
        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    // 改 提交
    const modifySubmitForms = () => {
      modifyRef.value.validate((valid) => {
        if(valid){
          let da = {}
          da.imgsetName = modifyData.value.imgsetName;
          da.represent = modifyData.value.describe;
          da.imgsetId = imgsetId

          console.log(da)
          datasets.modify(da).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("修改成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })
        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    // 下一页或上一页
    const handleCurrentChange = (newPage) => {
      console.log('Current page:', newPage);
      currentPage.value = newPage;
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      displayedData.length = 0
      displayedData.splice(start, end, ...listData.slice(start, end))
    };
    const handleSizeChange = (newSize) => {
      console.log('Current page:', newSize);
      pageSize.value = newSize;

      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      displayedData.length = 0
      displayedData.splice(start, end, ...listData.slice(start, end))
    }


    return {
      dialogVisible,
      handleBeforeClose,
      makeData,
      submitForms,
      formRef,
      listData,
      handleView,
      removeView,
      selectedKeys,
      modifyView,
      modifyVisible,
      modifyData,
      modifyRef,
      modifySubmitForms,
      Delete,
      Search,
      getList,
      Refresh,
      currentPage,
      pageSize,
      displayedData,
      handleCurrentChange,
      handleSizeChange,
      EditPen,
      mdeolRadio,
      imgset,
      imgsetValue,
      screenValue,
      screenOptions,
      CaretRight
    }
  }
}
</script>

<style scoped>
.list_data_box{
  width:100%;
  height: 100vh;
  padding:0;
  margin-top: 22px;
}
.el-table{
  width: 82% !important;
  height: 75%
}
.gui_box{
  background-color: rgb(255 255 255 / 60%);
  border-bottom: 2px solid #d9d9d9;
  width: 87.7%;
  height: 55px;
  margin-left:15px
}
.el-input-group{
  width: 30%;
  left: 10px;
}
.line{
  height: 25px;
  width: 87.7%;;
  background-color: rgb(255 255 255 / 60%);
  margin-left:15px;
  border-radius: 10px 10px 0 0;
}
/*.demo-pagination-block{*/
/*  width:82%*/
/*}*/
.data_box{
  width: 87.7%;
  text-align: initial;
  height: 140px;
  background-color: rgb(255 255 255 / 60%);
  /*border: 1px solid*/
  color: #8c8ca3;
  margin-left:15px;
  border-bottom: 2px solid #d9d9d9;
}
.data-box-content{
  flex: 1;
  border:1px solid white;
}
.data-box-content span{
  margin-left:20px;
  line-height: 30px;
}
</style>